import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_syntax_view/flutter_syntax_view.dart';
import 'package:im_app/im/util/FileUtil.dart';

import '../../../util/ImConstant.dart';

class CodeViewPage extends StatefulWidget {

  final String title;
  final String filePath;

  const CodeViewPage({ required this.title, required this.filePath, super.key});

  @override
  State<StatefulWidget> createState() => _CodeViewState();

}

class _CodeViewState extends State<CodeViewPage> {

  late Syntax _syntax;
  late String _code = '';

  @override
  void initState() {
    super.initState();

    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: _buildAppBar(context),
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        body: SyntaxView(
          code: _code,
          syntax: _syntax,
        )
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      leading: GestureDetector(
        child: const Icon(Icons.chevron_left, color: Colors.black),
        onTap: () => Navigator.of(context).pop(),
      ),
      centerTitle: true,
      title: Text(
        widget.title,
        style: const TextStyle(color: Colors.black, fontSize: ImConstant.IM_DEFAULT_SIZE),
      ),
    );
  }

  _loadData() async {
    Syntax? syntax = FileUtil.getCodeSyntax(widget.filePath);

    var file = File(widget.filePath);
    String code = await file.readAsString();
    setState(() {
      _code = code;
      _syntax = syntax!;
    });
  }

}